package com.ai.module.websocket.handler;

import com.ai.module.chat.common.base.ThreadLocalContext;
import com.ai.module.chat.common.constant.RedisKeyStringConstant;
import com.ai.module.chat.common.constant.StringConstant;
import com.ai.module.chat.config.advice.exception.BusinessException;
import com.ai.module.user.domain.vo.UserLoginInfo;
import com.ai.module.chat.util.RedisTemplateUtils;
import org.junit.platform.commons.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * webSocket握手拦截器
 *
 * @since 2023年12月16日16:57:52
 */
@Component
public class PortalHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    private final Logger logger = LoggerFactory.getLogger(PortalHandshakeInterceptor.class);


    /**
     * 初次握手访问前
     *
     * @param request
     * @param webSocketHandler
     * @param map
     * @return
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> map) {
        logger.info("HandshakeInterceptor beforeHandshake start...");
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
            ServletServerHttpResponse serverHttpResponse = ((ServletServerHttpResponse) response);
            String headToken = req.getHeader(StringConstant.TOKEN);
            dealToken(headToken);
        }
        logger.info("HandshakeInterceptor beforeHandshake end...");
        return true;
    }

    private static void dealToken(String headToken) {
        if (StringUtils.isBlank(headToken)){

            throw new BusinessException( 401,"请重新登录");
        }
        String userTokenKey = String.format(RedisKeyStringConstant.USER_INFO, headToken);

        UserLoginInfo userLoginInfo =  RedisTemplateUtils.get(userTokenKey);
        if (userLoginInfo ==null){

            throw new BusinessException("登录已过期,请重新登录",401);
        }
        ThreadLocalContext.set(StringConstant.USER_INFO,userLoginInfo);
        ThreadLocalContext.set(StringConstant.CURRENT_TIME,System.currentTimeMillis());
        ThreadLocalContext.setUserLoginInfo(userLoginInfo);
    }

    /**
     * 初次握手访问后，将前端自定义协议头Sec-WebSocket-Protocol原封不动返回回去，否则会报错
     *
     * @param request
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param e
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        logger.info("HandshakeInterceptor afterHandshake start...");

        logger.info("HandshakeInterceptor afterHandshake end...");
    }
}